package com.shengdan.pocket_file.pocketfile;

import android.annotation.SuppressLint;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {

    String TAG = "MainActivity";
    String ip = "";
    MethodChannel channel;

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);

        channel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(),
                "com.shengdan.pocket_file.pocketfile");
        channel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                switch (call.method) {
                    case "startBleBroadcast":
                        startBleBroadcast(call.arguments.toString());
                        break;

                }
            }
        });
    }




    private void startBleBroadcast(String ip) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//
//            ContentValues values = new ContentValues();
//
//            values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.getName());
//
//            values.put(MediaStore.MediaColumns.MIME_TYPE, getMimeType(file));
//
//            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
//
//            ContentResolver contentResolver = getContentResolver();
//
//            Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//
//            if (uri == null) {
//
//                return;
//
//            }
        Log.d(TAG, "startBleBroadcast: 开启蓝牙广播 本机IP：" + ip);
        this.ip = ip;
        Toast.makeText(this, ip, Toast.LENGTH_LONG).show();
        BluetoothUtils.getInstance().unReceiveBroadcastData(scanCallback);
        BluetoothUtils.getInstance().receiveBroadcastData(scanCallback);
        BluetoothUtils.getInstance().stopDataBroadcast(advertiseCallback);//保证只发一次
        BluetoothUtils.getInstance().sendDataBroadcast(ip, advertiseCallback);
    }

    //广播发送回调
    @SuppressLint("NewApi")
    AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            Log.d(TAG, "onStartSuccess: " + settingsInEffect.toString());
        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            Log.d(TAG, "onStartFailure: " + errorCode);
        }
    };

    //蓝牙扫描回调
    @SuppressLint("NewApi")
    ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            byte[] data = result.getScanRecord().getManufacturerSpecificData(0x15);
            String name = result.getScanRecord().getDeviceName();
            if (data != null && !TextUtils.isEmpty(name)) {
                String ipData = new String(data);
                String mac = result.getDevice().getAddress();
                Log.d(TAG, "蓝牙扫描回调 onScanResult: 发现一个设备,名称："+name+" ip地址:" + ipData+" mac地址："+mac);
                if (Utils.checkNetSegment("255.255.255.0",ip,ipData) == 0 && channel != null){
                    Log.d(TAG, "蓝牙扫描回调 onScanResult: 上述设备ip同网段：");
                    channel.invokeMethod("addDevice",JsonUtils.getBleDeviceJson(ipData,name,mac));
                }
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            Log.d(TAG, "蓝牙扫描回调 onBatchScanResults: " + results.size());
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.d(TAG, "蓝牙扫描回调 onScanFailed: " + errorCode);
        }
    };


}
